package response

import (
	"github.com/gin-gonic/gin"
	"gspeed/app/dist"
	"gspeed/app/utils/validate"
	"gspeed/bootstrap/global"
	"net/http"
)

// 1、确定struct有多少参数
type responseJson struct {
	httpStatus int         `json:"-"`
	Code       int         `json:"code"`
	Message    string      `json:"message"`
	Data       interface{} `json:"data"`
}

// 2、定义Option
type Option func(*responseJson)

// 3、每个参数都写一个方法，返回一个Option
func WithCode(code int) Option {
	// 传入新值，存储在option中
	return func(response *responseJson) {
		response.Code = code
	}
}

/*func WithMessage(message string) Option {
	return func(response *responseJson) {
		response.message = message
	}
}*/

func WithHttpStatus(httpStatus int) Option {
	return func(response *responseJson) {
		response.httpStatus = httpStatus
	}
}

func WithData(data interface{}) Option {
	return func(response *responseJson) {
		response.Data = data
	}
}

func Ok(ctx *gin.Context, opts ...Option) {
	lang := ctx.DefaultQuery("locale", global.Config.GetString("app.locale"))
	// 设置默认值
	response := &responseJson{
		httpStatus: http.StatusOK,
		Code:       dist.RequestSuccess,
		Data:       nil,
	}
	// 遍历option，覆盖struct参数的值
	for _, opt := range opts {
		opt(response)
	}

	message := ""
	if response.Code != dist.RequestSuccess {
		message = dist.Trans.CodeText(response.Code, lang)
	} else {
		message = dist.Trans.CodeText(dist.RequestSuccess, lang)
	}

	ctx.JSON(http.StatusOK, &responseJson{
		Code: dist.RequestSuccess,
		Data: response.Data,
		//Message: response.Message,
		Message: message,
	})
	return
}

func Err(ctx *gin.Context, opts ...Option) {
	lang := ctx.DefaultQuery("locale", global.Config.GetString("app.locale"))
	// 设置默认值
	response := &responseJson{
		httpStatus: http.StatusBadRequest,
		Code:       dist.RequestFail,
		Data:       nil,
		Message:    dist.Trans.CodeText(dist.RequestFail, lang),
	}
	for _, opt := range opts {
		opt(response)
	}
	ctx.JSON(response.httpStatus, &responseJson{
		Code:    response.Code,
		Data:    validate.Validate.Translate(response.Data, lang),
		Message: dist.Trans.CodeText(response.Code, lang),
	})
	ctx.Abort()
	return
}
